package com.feng.newconfig.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.feng.common.model.Result;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 统一限流降级返回值
 * SentinelWebAutoConfiguration ->SentinelWebInterceptor->AbstractSentinelInterceptor->BaseWebMvcConfig->BlockExceptionHandler
 * sentinel给了一个默认实现类，当触发限流时，返回的是"Blocked by Sentinel (flow limiting)"
 * 通过实现BlockExceptionHandler，定义统一返回值
 */
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.print(JSON.toJSON(Result.fail("触发限流")));
        out.flush();
        out.close();
    }
}